﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Facebook;
using System.Web.Mvc;
using Sprint1.Models;
using System.Web.Security;
using System.Net;
using System.IO;
//////////////
/////////////
namespace Sprint1.Controllers
{
    public class StudentController : Controller
    {
        #region Hamed 
        [Authorize]
        public ActionResult Index()
        {
            return View();
        }
        [HttpGet]
        public ActionResult Register()
        {
            //Log out the user if he was logged in 
            bool user = (System.Web.HttpContext.Current.User != null) && System.Web.HttpContext.Current.User.Identity.IsAuthenticated;
            if (user)
            {
                FormsAuthentication.SignOut();
            }
            return View();
        }
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Register(Student student)
        {

            if (ModelState.IsValid)
            {
                try
                { 
                    #region new user
                    using (StudyDatabaseEntities dc = new StudyDatabaseEntities())
                    {
                        var query = from st in dc.Students
                                    where st.Email == student.Email
                                    select st;
                        var exists = query.SingleOrDefault();
                        if (exists == null)
                        {
                            dc.Students.Add(student);
                            dc.SaveChanges();
                            ModelState.Clear();
                           ViewBag.messege = "Created Successfully";
                          // FormsAuthentication.RedirectFromLoginPage(exists.Email, true);
                        }
                        else
                        {
                            ViewBag.messege = string.Format("{0} Already Exists ", student.Email);
                        }
                    }
                    #endregion
                }
                catch (Exception ex)
                {///////////////////Developer Comment //////////////////////
                    ViewBag.messege = ex.InnerException.Message;
                }
            }
            return View();

        }
        [HttpGet]
        public ActionResult Login()
        {
            return View();
        }
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Login(StudentLoginModel student)
        {
            if (ModelState.IsValid)
            { 
                using (StudyDatabaseEntities db = new StudyDatabaseEntities())
                {
                    var exists = db.Students.Where(st => st.Email.Equals(student.Email) && st.Password.Equals(student.Password)).FirstOrDefault();
                    if (exists != null)
                    {
                        //will always redirect to default if i didn't pass new { ReturnUrl = Request.QueryString["ReturnUrl"] }
                        //with the HTML  form 
                        //http://stackoverflow.com/questions/4246606/formsauthentication-getredirecturl-always-returns-the-default
                        //FormsAuthentication.RedirectFromLoginPage(exists.Email, true);
                          FormsAuthentication.SetAuthCookie(exists.Email, true);
                        return Redirect("FindCourse");
                    }
                    else
                    {
                        ViewBag.message = "Invalid Email or Password ";
                    }
                }
            }
            else//modelstate is not valid 
            {
                var errors = ModelState.Where(x => x.Value.Errors.Count > 0).Select(x => new { x.Key, x.Value.Errors }).ToArray();
            }
            return View(student);
        }
        #endregion 
        #region Adel
        [HttpGet]
        [Authorize]
        public ActionResult FindCourse()
        {
           /* StudyDatabaseEntities db = new StudyDatabaseEntities();
            return View(db.Courses);*/
            return View();
        }
        [HttpPost]
        [Authorize]
        public ActionResult FindCourse(string searchTerm)
        {
            using (StudyDatabaseEntities db = new StudyDatabaseEntities())
            {
                try
                {
                    List<Course> courses;
                    courses = db.Courses.Where(s => s.Name.Contains(searchTerm)).ToList();
                    return View(courses);
                }
                catch (Exception ex)
                {
                    ViewBag.message = ex.Message;
                    return View();
                }
            }
        }
        public JsonResult GetCourses(string term)
        {
            using (StudyDatabaseEntities db = new StudyDatabaseEntities())
            {
                try
                {
                    List<string> courses;
                    courses = db.Courses.Where(s => s.Name.Contains(term))
                        .Select(x => x.Name).ToList();
                    return Json(courses, JsonRequestBehavior.AllowGet);
                }
                catch (Exception ex)
                {
                    //DEVELOPER 
                    ViewBag.message = ex.Message;
                    return Json(new { ex.Message });
                }

            }
        }
        #endregion
        #region Ali
        public ActionResult ViaFacebook()
        {
            string app_id = "618386488238601";
            string app_secret = "dfc8420e9b078b7308e681a935995352";
            string scope = "email";
            Student Student = new Student(); // my student object. 
            // for redirect to fb page and enter his e-mail
            if (Request["code"] == null)
            {
                Response.Redirect(string.Format(
                    "https://www.facebook.com/dialog/oauth?client_id={0}&redirect_uri={1}&scope={2}",
                    app_id, Request.Url.AbsoluteUri, scope));
            }
            else
            {
                Dictionary<string, string> tokens = new Dictionary<string, string>(); // for save access_token.
                string url = string.Format("https://graph.facebook.com/oauth/access_token?client_id={0}&redirect_uri={1}&code={2}&client_secret={3}",
                    app_id, Request.Url.AbsoluteUri, Request["code"].ToString(), app_secret);
                // URL for accessing with app_id and secret to show permissions.
                HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
                using (HttpWebResponse response = request.GetResponse() as HttpWebResponse) // request for permission
                {
                    StreamReader reader = new StreamReader(response.GetResponseStream());
                    string vals = reader.ReadToEnd();
                    // get access_token
                    foreach (string token in vals.Split('&'))
                    {
                        tokens.Add(token.Substring(0, token.IndexOf("=")),
                            token.Substring(token.IndexOf("=") + 1, token.Length - token.IndexOf("=") - 1));
                    }
                }
                string access_token = tokens["access_token"]; // get access token into a string
                FacebookClient fb = new FacebookClient(access_token); // create a new facebookclient
                var results = (IDictionary<string, object>)fb.Get("/me"); // get all fb account info into result using dictionary
                Student.Name = results["name"].ToString();
                Student.Email = results["email"].ToString();
                Student.Password = "Hamed12345";//results["email"].ToString();
            }
            if (Student.Email != null)
            {
                try
                {
                    using (StudyDatabaseEntities db = new StudyDatabaseEntities())
                    {
                        var exists = db.Students.Where(st => st.Email.Equals(Student.Email) && st.Password.Equals(Student.Password)).FirstOrDefault();
                        // if email is already exist .. then LOGIN with his email
                        if (exists != null)
                        {
                            FormsAuthentication.SetAuthCookie(exists.Email, true);
                            return Redirect("FindCourse");
                        }
                        // if email doesn't exist, register him.
                        else
                        {
                            db.Students.Add(Student);
                            db.SaveChanges();
                            FormsAuthentication.RedirectFromLoginPage(Student.Email, true);
                            return Redirect("FindCourse");
                        }
                    }
                }
                catch (Exception ex)
                {
                    ViewBag.message = ex.Message; // developer
                    return View();
                }
            }
            else
            {
                ViewBag.message = "Failed";
                return View(); // if student.email == null, where will navigate to !?
            }
        } // end LoginViaFacebook method.
        #endregion
        #region Hagar
        StudyDatabaseEntities  db = new StudyDatabaseEntities();
       [Authorize]
        public ActionResult MyCourses()
        {
            string email = HttpContext.User.Identity.Name.ToString();
           return View(db.Students.Single(i => i.Email == email).Courses.ToList());
        }
      [Authorize]
        public ActionResult CourseInfo(int? id)
        {
            string email = HttpContext.User.Identity.Name.ToString();
            int studentid = db.Students.SingleOrDefault(s=>s.Email==email).Id;
            if (id == null)
            {
                return RedirectToAction("MyCourses");
            }
            Course C = db.Courses.Single(c => c.Id == id);
            if (C.Students.ToList().Exists(s => s.Id == studentid))
            {
                return View(C);
            }
            else
            {
                Session["requestid"] = id;
                return RedirectToAction("CourseCode");
            }
        }
        [HttpGet]
        [Authorize]
        public ActionResult CourseCode()
        {
            return View();
        }
        [HttpPost]
        [Authorize]
        public ActionResult CourseCode(FormCollection formCollection)
        {
            string email = HttpContext.User.Identity.Name.ToString();
            int studentid = db.Students.SingleOrDefault(s => s.Email == email).Id;
            if ((int?)Session["requestid"] != null)
            {
                int id = (int)Session["requestid"];
                Course C = db.Courses.Single(c => c.Id == id);

                if (C.Code == formCollection["txtBoxCourseCode"])
                {
                    //enroll el user
                    Student S = db.Students.Single(i => i.Id == studentid);
                    C.Students.Add(S);
                    S.Courses.Add(C);
                    db.SaveChanges();
                    Session.Contents.Remove("requestid");
                      Session["requestid"] = null;
                    return RedirectToAction("CourseInfo");
                }
                else
                {
                    ViewBag.message = "the code you entered is not valid , please check course instructor";
                    Session.Contents.Remove("requestid");
                    return View();
                }
            }
            else
            {
                return RedirectToAction("MyCourses");
            }
        }
        #endregion
    }
}